package handler

import (
	"2302a/testyuekao/api/request"
	"2302a/testyuekao/api/resp"
	"2302a/testyuekao/internal/dao"
	"2302a/testyuekao/internal/model"
	"github.com/gin-gonic/gin"
	"time"
)

func AchieveReservation(c *gin.Context) {
	var req request.AchieveReservation

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var user model.Users
	dao.GetOneById(c.GetUint("userId"), &user)
	if user.UType != 1 {
		resp.Error(c, 100002, "该权限不足", nil)
		return

	}
	ReservationTime, err := time.Parse(time.DateTime, req.ReservationTime)

	if err != nil {
		resp.Error(c, 100003, "时间格式不对", err.Error())
		return
	}
	if time.Now().Unix() > ReservationTime.Unix() {
		resp.Error(c, 100004, "预约时间小于当前时间", nil)
		return
	}
	var house model.Houses
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		resp.Error(c, 100005, "房源不存在", nil)
		return
	}
	dao.Create(&model.HouseReservations{UserId: c.GetUint("userId"), HouseId: house.Id, ReservationTime: ReservationTime})
	resp.Success(c, "实现预约看房成功", true)
}

func CancelReservation(c *gin.Context) {
	var req request.CancelReservation

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var reservation model.HouseReservations
	dao.GetOneById(req.Id, &reservation)
	if reservation.Id == 0 {
		resp.Error(c, 100002, "取消预约看房失败", nil)
		return
	}
	dao.Delete(&model.HouseReservations{Id: req.Id})
	resp.Success(c, "取消看房成功", true)
}
